<template>
  <div class="transQuery_main">
    <a-form>
      <a-row :gutter="8">
        <a-col :span="8">
          <a-form-item>
            <div
              style="display: flex;flex-direction: row;justify-content: space-around;align-items: center;"
            >
              <div class="searchTitle">下级合作机构：</div>
              <a-select
                showSearch
                placeholder="下级合作机构"
                @change="handleChange"
                :filterOption="filterOption"
                :options="PartnersList"
                v-model="query.data.memberNo"
              ></a-select>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item>
            <div>
              <a-button class="button_sty" type="primary" @click="handleSearch">查询</a-button>
              <a-button class="button_sty" type="primary" @click="reset">重置</a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <h4>活动名称：{{activeName}}</h4>
    <a-table
      size="middle"
      :scroll="{ y: '38vh' }"
      :columns="columns"
      :dataSource="list"
      :pagination="false"
      :rowKey="record => record.memberNo + 1"
    >
      <!-- <span slot="typeTitle">
        <span v-if="this.list[0].type == 'first_fee'">首笔交易扣除服务费</span>
        <span v-if="this.list[0].type == 'first_trans'">首笔交易大于</span>
        <span v-if="this.list[0].type == 'sum_trans'">累计交易大于</span>
      </span>-->
      <span slot="transTime" slot-scope="record">{{record.transTime | timeFilter}}</span>
      <span slot="amount" slot-scope="record">{{(record.amount/100).toFixed(2)}}</span>
      <span
        slot="activateForfeitAmount"
        slot-scope="record"
      >{{record.activateForfeitAmount ? record.activateForfeitAmount : '未配置'}}</span>
      <span
        slot="rewardAmountDesc"
        slot-scope="record"
      >{{record.rewardAmountDesc ? record.rewardAmountDesc : '未配置'}}</span>
      <span
        slot="activateRewardAmount"
        slot-scope="record"
      >{{record.activateRewardAmount ? record.activateRewardAmount : '未配置'}}</span>
      <span
        slot="forfeitAmountDesc"
        slot-scope="record"
      >{{record.forfeitAmountDesc ? record.forfeitAmountDesc : '未配置'}}</span>
      <span slot="action" slot-scope="record" style="display: felx;justify-content: space-around;">
        <span
          @click="record.allowActivateConfig ? showVisible(record.subjectId,record.memberNo) : ''"
          :class="record.allowActivateConfig ? 'textcolor' : 'nocolor'"
        >激活考核</span>
        <span
          @click="record.allowTransConfig ? showTransVisible(record.subjectId,record.memberNo,record.merchantName) : ''"
          :class="record.allowTransConfig ? 'textcolor' : 'nocolor'"
        >交易量考核</span>
      </span>
    </a-table>
    <a-pagination
      @change="onPageChange"
      :current="pagination.current"
      :total="pagination.total"
      :pageSize="query.pageSize"
      style="margin-top: 20px"
    />

    <a-modal
      @ok="handleOk"
      @cancel="handleCancel"
      v-model="visible"
      title="激活考核"
      :footer="null"
      :maskClosable="false"
      centered
    >
      <h5>以下均指单台终端</h5>
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="toSubmit">
        <a-row :gutter="8">
          <a-col :span="24">
            <a-form-item label="激活指标" :label-col="{ span: 6}" :wrapper-col="{ span: 15,offset:1 }">
              <span
                v-if="activationShowData.activateTargetTemplate.type == 'first_fee'"
              >首笔交易商户支付服务费{{activationShowData.activateTargetTemplate.amount | cashfilter}}</span>
              <span
                v-if="activationShowData.activateTargetTemplate.type == 'first_trans'"
              >首笔交易≥{{activationShowData.activateTargetTemplate.amount | cashfilter}}</span>
              <span
                v-if="activationShowData.activateTargetTemplate.type == 'sum_trans'"
              >累计交易≥{{activationShowData.activateTargetTemplate.amount | cashfilter}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="激活" :label-col="{ span: 6}" :wrapper-col="{ span: 15,offset:1 }">
              返现&ensp;
              <a-input-number
                v-decorator="[
          'rewardAmount',
          { rules: [{ required: true, message: '请填写激活返现金额！' }] },
        ]"
                :min="0"
                :max="10000"
                :step="1"
                :formatter="value => Math.round(value)"
                @change="onChange"
              />&ensp; 元
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="未激活" :label-col="{ span: 6}" :wrapper-col="{ span: 15,offset:1 }">
              <!-- <a-input addonBefore="扣款" addonAfter="元" /> -->
              扣款&ensp;
              <a-input-number
                v-decorator="[
          'forfeitAmount',
          { rules: [{ required: true, message: '请填写未激活扣款金额！' }] },
        ]"
                :min="0"
                :max="10000"
                :step="1"
                :formatter="value => Math.round(value)"
                @change="onChange"
              />&ensp; 元
            </a-form-item>
          </a-col>
        </a-row>
        <div style="text-align: center;margin-top: 25px;">
          <a-button type="primary" style="width:100px;" :loading="toLoading" html-type="submit">提交</a-button>
        </div>
      </a-form>
    </a-modal>

    <a-modal
      width="650px"
      @ok="transHandleOk"
      @cancel="transHandleCancel"
      v-model="transvisible"
      title="交易量考核"
      :footer="null"
      :maskClosable="false"
      centered
    >
      <a-form :form="transform" @submit="toTransSubmit">
        <a-row :gutter="8">
          <!-- <a-col :span="24">
                        <a-form-item label='激活指标' :label-col="{ span: 6}" :wrapper-col="{ span: 15,offset:1 }">
                            <span>首笔交易商户支付服务费300元</span>
                        </a-form-item>
          </a-col>-->
          <h4>自{{transRuleDesc}}交易之日起:</h4>

          <a-col v-for="(item,index) in addUpList" :span="24" :key="index">
            <a-form-item>
              第{{item.startDay}}至{{item.endDay}}天，交易量累计{{item.typeName}}{{item.targetAmount | cashfilter}}，返现&ensp;
              <a-input-number
                v-decorator="[
          `addUpListValue[${index}]`,
          { rules: [{ required: true, message: '请填写激活返现金额！' }] },
        ]"
                :min="0"
                :max="10000"
                :step="1"
                :formatter="value => Math.round(value)"
                @change="onChange"
              />&ensp; 元
            </a-form-item>
          </a-col>

          <h4>自{{transRuleDesc}}交易之日起:</h4>
          <a-col v-for="(item,index) in DeductionList" :span="24" :key="index + '-'">
            <a-form-item>
              第{{item.startDay}}至{{item.endDay}}天，交易量累计{{item.typeName}}{{item.targetAmount | cashfilter}}，扣款&ensp;
              <a-input-number
                v-decorator="[
          `DeductionListValue[${index}]`,
          { rules: [{ required: true, message: '请填写未激活扣款金额！' }] },
        ]"
                :min="0"
                :max="10000"
                :step="1"
                :formatter="value => Math.round(value)"
                @change="onChange"
              />&ensp; 元
            </a-form-item>
          </a-col>
        </a-row>
        <div style="text-align: center;margin-top: 25px;">
          <a-button
            type="primary"
            style="width:100px;"
            :loading="toTransLoading"
            html-type="submit"
          >提交</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import AForm from "ant-design-vue/es/form/Form";
import ATabs from "ant-design-vue/es/tabs";
import AFormItem from "ant-design-vue/es/form/FormItem";
import AInput from "ant-design-vue/es/input/Input";
import AIcon from "ant-design-vue/es/icon";
import AInputGroup from "ant-design-vue/es/input/Group";
import AButton from "ant-design-vue/es/button/button";
import ACol from "ant-design-vue/es/grid/Col";
import ARow from "ant-design-vue/es/grid/Row";
import ACheckbox from "ant-design-vue/es/checkbox/Checkbox";
import AAlert from "ant-design-vue/es/alert/index";
import pick from "lodash.pick";
import moment from "moment";
import api from "@/common/api";
const ATabPane = ATabs.TabPane;

const columns = [
  {
    title: "下级合作机构",
    dataIndex: "merchantName",
    width: "15%",
    align: "center"
  },
  // {
  //   dataIndex: "activateAmount",
  //   scopedSlots: { title: "typeTitle" },
  //   width: "16%",
  //   align: "center"
  // },
  {
    title: "激活返现",
    scopedSlots: { customRender: "activateRewardAmount" },
    width: "15%",
    align: "center"
  },
  {
    title: "未激活扣款",
    scopedSlots: { customRender: "activateForfeitAmount" },
    width: "15%",
    align: "center"
  },
  {
    title: "交易量达标返现",
    scopedSlots: { customRender: "rewardAmountDesc" },
    width: "15%",
    align: "center"
  },
  {
    title: "交易量未达标扣款",
    scopedSlots: { customRender: "forfeitAmountDesc" },
    width: "20%",
    align: "center"
  },
  // { title: "交易状态", dataIndex: "statusName", width: '12%', align: 'center' },
  // { title: "结算状态", dataIndex: "settleStatus", width: '11%', align: 'center' },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    width: "20%",
    align: "center"
  }
];

export default {
  name: "lowerLevelParam",
  components: {
    AAlert,
    ACheckbox,
    ACol,
    ARow,
    AButton,
    AInputGroup,
    AIcon,
    AInput,
    AFormItem,
    ATabPane,
    ATabs,
    AForm
  },

  data() {
    return {
      today: new Date(),
      columns,
      isClear: false,
      momentDate: moment(new Date()),
      excelurl: "",
      activeName: "",
      statusList: [
        // { label: "全部", value: "all" },
        // { label: "交易成功", value: "payed" },
        // { label: "交易失败", value: "failed" },
        // { label: "待支付", value: "ordered" },
      ],
      toLoading: false,
      toTransLoading: false,
      subjectTransMember: [],
      addNewUpList: [],
      DeductionNewList: [],
      SettleStatusList: [],
      PartnersList: [],
      query: {
        page: 1,
        pageSize: 10,
        data: {
          subjectId: "",
          memberNo: null
        }
      },
      activationShowData: {
        subjectActivateMember: {},
        activateTargetTemplate: {}
      },
      formShow: true,
      activationData: {
        id: "",
        subjectId: "",
        rewardAmount: "",
        forfeitAmount: "",
        toMemberNo: null
      },
      transRuleDesc: "",
      transData: {
        subjectId: "",
        subjectName: "",
        toMemberNo: null,
        toMemberName: null,
        targetRequestList: []
      },
      pagination: { current: null, total: null },
      visible: false,
      transvisible: false,
      form: this.$form.createForm(this),
      transform: this.$form.createForm(this),
      error: "",
      loginpwd: "",
      loginpwd2: "",
      login: false,
      addUpList: [],
      DeductionList: [],
      list: [],
      count: null,
      payedCount: null,
      totalAmount: null,
      loading: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 14, offset: 1 },
          md: { span: 14, offset: 1 }
        }
      }
    };
  },
  watch: {},
  filters: {
    timeFilter: function(value) {
      if (value) {
        let year = value.substring(0, 2);
        let mouth = value.substring(2, 4);
        let day = value.substring(4, 6);
        return year + ":" + mouth + ":" + day;
      }
    },
    cashfilter(value) {
      // return parseFloat(value / 100).toFixed(2) + "元";
      return value + "元";
    }
  },
  computed: {},
  created() {
    this.query.data.subjectId = this.$route.params.id;
  },
  mounted() {
    this.PartnersQuery();
    this.handleSearch();
  },
  methods: {
    moment,
    onPageChange: function(page, pageSize) {
      console.info(page, pageSize);
      this.query.page = page;
      this.query.pageSize = pageSize;
      this.handleSearch();
    },
    reset() {
      this.query.data.memberNo = null;
    },
    handleSearch() {
      this.list = [];
      this.loading = true;
      console.info(this.query);
      api.lowerLevelParamQuery(
        this.query,
        res => {
          console.info(res);
          if (res.code == "OK") {
            this.loading = false;
            this.list = res.data.list;
            this.activeName = res.data.name;
            this.transData.subjectName = res.data.name;
            // this.list.forEach(function(item) {
            //   item.activateAmount = item.activateAmount.toFixed(2);
            // });
            this.pagination.current = res.data.current;
            this.pagination.total = res.data.total;
            // this.count = res.total; //总笔数
            // this.payedCount = res.payedCount; //成功笔数
            // this.totalAmount = res.totalAmount.toFixed(2); //总金额
          } else {
            this.loading = false;
            // this.$message.info(res.message)
            this.list = [];
            this.pagination.current = 1;
            this.pagination.total = 1;
            return false;
          }
        },
        err => {
          console.log("err", err);
          if (err) {
            this.loading = false;
          }
        }
      );
    },
    // 激活考核查询
    activationAssessmentQuery(id, memberNo) {
      this.activationData.subjectId = id;
      this.activationData.toMemberNo = memberNo;
      let data = {
        subjectId: id,
        toMemberNo: memberNo
      };
      api.activationAssessmentQuery(
        data,
        res => {
          console.log(res);
          this.activationShowData = res.data;
          if (res.data.subjectActivateMember) {
            this.activationData.id = res.data.subjectActivateMember.id;
            this.$nextTick(() => {
              this.form.setFieldsValue({
                rewardAmount: res.data.subjectActivateMember.rewardAmount,
                forfeitAmount: res.data.subjectActivateMember.forfeitAmount
              });
            });
          }
        },
        err => {}
      );
    },
    // 交易量考核查询
    transAssessmentQuery(id, memberNo, merchantName) {
      this.transData.subjectId = id;
      this.transData.toMemberNo = memberNo;
      this.transData.toMemberName = merchantName;
      let data = {
        subjectId: id,
        toMemberNo: memberNo
      };
      this.formShow = true;
      api.transAssessmentQuery(
        data,
        res => {
          var self = this;
          console.log(res);
          this.addUpList = [];
          this.DeductionList = [];
          this.addNewUpList = [];
          this.DeductionNewList = [];
          if (res.code == "OK") {
            this.transRuleDesc = res.data.transRuleDesc;
            this.subjectTransMember = res.data.subjectTransMember;
            console.log(this.subjectTransMember.length);
            if (this.subjectTransMember.length > 0) {
              this.subjectTransMember.forEach((item, index) => {
                if (item.type == "achieve") {
                  this.addNewUpList.push(item);
                } else if (item.type == "un_achieve") {
                  this.DeductionNewList.push(item);
                }
              });

              // 返现赋值
              let valueList = [];
              self.addNewUpList.forEach((item, index) => {
                valueList.push(item.rewardAmount);
              });
              console.log("valueList", valueList);
              // 扣款赋值
              let valueList1 = [];
              self.DeductionNewList.forEach((item, index) => {
                valueList1.push(item.rewardAmount);
              });
              console.log("valueList1", valueList1);
              // let returnedTarget = Object.assign(
              //   { addUpList: valueList },
              //   { DeductionList: valueList1 }
              // );

              // self.$nextTick(() => {
              setTimeout(function() {
                self.transform.setFieldsValue({
                  addUpListValue: valueList,
                  DeductionListValue: valueList1
                });
                // self.transform.setFieldsValue(
                //   pick(returnedTarget, "addUpList", "DeductionList")
                // );
              }, 100);
              // });

              // self.$nextTick(() => {
              //   self.transform.setFieldsValue({
              //     DeductionList: valueList1
              //   });
              // });
            }

            res.data.subjectTransTargetTemplate.forEach((item, index) => {
              if (item.type == "achieve") {
                this.addUpList.push(item);
              } else if (item.type == "un_achieve") {
                this.DeductionList.push(item);
              }
            });
          }
        },
        err => {}
      );
    },
    PartnersQuery() {
      let data;
      api.lowerLevelQuery(
        data,
        res => {
          console.log(res);
          if (res.code == "OK") {
            this.PartnersList = res.data;
          }
        },
        err => {}
      );
    },
    handleChange(value) {
      console.log(`selected ${value}`);
      this.handleSearch();
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    goDetail(id) {
      console.log(id);
      this.$router.push(`/marketing/payInstalmentsQueryDetail/${id}`);
    },
    onChange(value) {
      console.log("changed", value);
    },
    handleOk(e) {
      setTimeout(() => {
        this.visible = false;
      }, 10);
    },
    handleCancel(e) {
      this.visible = false;
    },
    transHandleOk(e) {
      setTimeout(() => {
        this.transvisible = false;
      }, 10);
    },
    transHandleCancel(e) {
      this.transvisible = false;
    },
    showVisible(id, memberNo) {
      this.visible = true;
      this.activationAssessmentQuery(id, memberNo);
    },
    showTransVisible(id, memberNo, merchantName) {
      this.transvisible = true;
      this.formShow = false;
      this.transAssessmentQuery(id, memberNo, merchantName);
    },
    toSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);

          this.activationData.rewardAmount = values.rewardAmount;
          this.activationData.forfeitAmount = values.forfeitAmount;
          this.toLoading = true;
          api.activationAssessment(
            this.activationData,
            res => {
              this.toLoading = false;
              console.log(res);
              if (res.code == "OK") {
                this.$message.success("提交成功！");
                this.handleSearch();
                this.visible = false;
              }
            },
            err => {
              this.toLoading = false;
            }
          );
        }
      });
    },
    toTransSubmit(e) {
      e.preventDefault();
      this.transform.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          let arrList1 = [];
          let arrList2 = [];
          let arrList = [];
          arrList1 = this.addUpList.map((item, index) => {
            return {
              subjectTransTargetId: item.id,
              rewardAmount: values.addUpListValue[index],
              id:
                this.addNewUpList.length > 0
                  ? this.addNewUpList[index].id
                  : null
            };
          });
          arrList2 = this.DeductionList.map((item, index) => {
            return {
              subjectTransTargetId: item.id,
              rewardAmount: values.DeductionListValue[index],
              id:
                this.DeductionNewList.length > 0
                  ? this.DeductionNewList[index].id
                  : null
            };
          });
          console.log("arrList1", arrList1);
          console.log("arrList2", arrList2);
          arrList = arrList1.concat(arrList2);
          // this.transData.rewardAmount = values.rewardAmount;
          // this.transData.forfeitAmount = values.forfeitAmount;
          this.transData.targetRequestList = arrList;
          this.toTransLoading = true;
          api.transAssessment(
            this.transData,
            res => {
              this.toTransLoading = false;
              console.log(res);
              if (res.code == "OK") {
                this.$message.success("提交成功！");
                this.handleSearch();
                this.transvisible = false;
              }
            },
            err => {
              this.toTransLoading = false;
            }
          );
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
span {
  cursor: pointer;
}

span {
  cursor: pointer;
}

.formGroupTitle {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
}

.ant-tabs-nav {
  float: right;
}

.amountColor {
  color: #29a576;
  font-weight: 400;
}

.amountSize {
  font-size: 20px;
  padding: 0 5px;
}

.expand {
  display: flex;
  align-items: center;
  justify-content: center;
}

.transQuery_main {
  /* padding: 30px 40px; */
  padding: 70px;
}

.button_sty {
  width: 120px;
  margin-left: 15px;
}

.searchTitle {
  width: 150px;
}

.textcolor {
  color: #1890ff;
}
.nocolor {
  color: #a6a6a6;
}

/deep/.ant-input-group-addon {
  background: #fff;
}
</style>